package com.cj.startup.run

import android.content.Context
import android.os.Process
import android.util.Log
import com.cj.startup.Startup
import com.cj.startup.StartupResult
import com.cj.startup.event.StartupObservable
import com.cj.startup.event.StartupObserve
import com.cj.startup.manager.StartupCacheManager
import com.cj.startup.manager.StartupManager
import java.lang.RuntimeException

class StartupRunnable(
    private val context: Context,
    private val startup: Startup<*>,
    private val startupManager: StartupManager
) : Runnable {

    override fun run() {
        val clazz = startup.javaClass
        if(!StartupCacheManager.hasInitialize(clazz)){
            StartupCacheManager.saveInitializingComponent(clazz)
        }else{
            throw RuntimeException("Startup已经有过初始化：${clazz}")
        }
        StartupObservable.notifyObserver(StartupObserve.Event.WAIT,clazz,null)
        Process.setThreadPriority(startup.getThreadPriority())
        startup.toWait()
        StartupObservable.notifyObserver(StartupObserve.Event.START,clazz,null)
        val startTime = System.currentTimeMillis()
        val result = startup.create(context)
        val endTime = System.currentTimeMillis()
        Log.i("Startup","${clazz}任务执行时间：${endTime - startTime}毫秒")
        //保存任务的返回结果
        StartupCacheManager.saveInitializedComponent(clazz, StartupResult(result))
        StartupCacheManager.removeInitializingComponent(clazz)
        StartupObservable.notifyObserver(StartupObserve.Event.FINISHED,clazz,result)
        StartupObservable.removeObserver(clazz)
        //当前任务执行完成后，调用后序任务的toNotify()
        startupManager.notifyChildren(startup)
    }
}